package com.hspedu.newData.dmsxl.链表.合并链表;

import com.hspedu.newData.dmsxl.ds.ListNode;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-27 
 * @Version: 1.0
 */

public class LC23合并k个有序链表 {

    // 顺序合并，依次合并，每次两两合并
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode ans = null;
        for (int i = 0; i < lists.length; i++) {
            ans = mergeTwoLists(ans,lists[i]);
        }
        return ans;
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2){
        if (list1 == null || list2 == null){
            return list1 == null ? list2 : list1;
        }
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        while(list1 != null && list2 != null){
            if (list1.val <= list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        cur.next = list1 == null ? list2 : list1;
        return dummy.next;
    }

    // todo 分治合并

    // todo 优先队列
}
